package cn.sykj.car.filter;

import cn.sykj.car.annotation.Money;
import cn.sykj.car.common.Const;
import com.alibaba.fastjson.serializer.ValueFilter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.math.BigDecimal;

@Slf4j
public class MoneyValueFilter implements ValueFilter {
    @Override
    public Object process(Object object, String name, Object value) {
        if (null == value) {
            return value;
        }
        if(!(value instanceof Integer) && !(value instanceof Long) && !(value instanceof String)) {
            return value;
        }
        try {
            Field field = object.getClass().getDeclaredField(name);
            Money money = field.getAnnotation(Money.class);
            if (money == null) {
                return value;
            }
            if (value instanceof Integer){
                Integer val = (Integer)value;
                BigDecimal realVal = new BigDecimal(val);
                return realVal.divide(new BigDecimal(100), Const.MONEY_SCALE, BigDecimal.ROUND_HALF_EVEN);
            }
            if (value instanceof Long){
                Long val = (Long)value;
                BigDecimal realVal = new BigDecimal(val);
                return realVal.divide(new BigDecimal(100), Const.MONEY_SCALE, BigDecimal.ROUND_HALF_EVEN);
            }
            if (value instanceof String){
                String val = (String)value;
                BigDecimal realVal = new BigDecimal(val);
                return realVal.divide(new BigDecimal(100), Const.MONEY_SCALE, BigDecimal.ROUND_HALF_EVEN);
            }
            else {
                return value;
            }
        } catch (NoSuchFieldException e) {
//            log.error("当前数据类型为{},值为{}", object.getClass(), value);
            return value;
        }
    }
}
